using UnityEngine;
using Vector3 = UnityEngine.Vector3;

public class BounceBallDrop : MonoBehaviour
{
    public const float BOUNCE_MIN = 0.5f;
    public const float BOUNCE_MAX = 1.0f;
    [HideInInspector]
    [Range(BOUNCE_MIN, BOUNCE_MAX)]
    public float attenuation = 0.7f;

    public AudioClip clip;

    [Tooltip("modify the gravity effect")]
    private float coef = 50;
    [Tooltip("the attenuation of each collision")]
    
    private Rigidbody _rigidbody;
    private float gravity = -9.8f;

    private float time;

    private float jumpHeight;
    // Start is called before the first frame update
    void Start()
    {
        _rigidbody = GetComponent<Rigidbody>();
        Restart();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        time += Time.fixedDeltaTime;
        _rigidbody.AddForce(Vector3.up * _rigidbody.mass * gravity);

        if (_rigidbody.velocity.y > 0)
        {
            jumpHeight += -0.5f * gravity * Time.fixedDeltaTime * Time.fixedDeltaTime;
        }
        else if (transform.position.y < -0.5f)
        {
            OnCollisionEnter(null);
        }
    }

    private void OnCollisionEnter(Collision other)
    {
        // Debug.Log($"Collision: {other.gameObject.name}");
        AudioSource.PlayClipAtPoint(clip, transform.position);
        
        _rigidbody.AddForce(-Vector3.up * _rigidbody.mass * time * gravity * coef * attenuation);
        time = 0;
        jumpHeight = 0;
    }

    public void Restart()
    {
        transform.position = new Vector3(0, 10, 0);
        _rigidbody.velocity = Vector3.zero;
        time = 0;
    }
}
